package com.jiahe.video.util;


import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 企微
 * @author YanDongwang
 * @since 1.0.1
 */
public class WeComUtil {

    private WeComUtil(){}

    /**
     * 发送【文本】消息
     * @param webHook
     * @param text
     * @return
     */
    public static boolean sendText(String webHook,String text){
        return sendText(webHook,text,new HashSet<String>());
    }

    /**
     * 发送【文本】消息
     * @param webHook
     * @param textStr
     * @param atPhone
     * @return
     */
    public static boolean sendText(String webHook, String textStr, Set<String> atPhone){
        String json = JSON.toJSONString(buildTextMsg(textStr,atPhone));
        return send(webHook,json);
    }

    /**
     * 向腾讯发送请求
     * @param webHook
     * @param json
     * @return
     */
    private static boolean send(String webHook,String json){
        String result;
        try {
            result = HttpRequest.post(webHook).body(json).execute().body();
        }catch (Exception e){
            throw new RuntimeException("发送失败，" + e.getMessage());
        }
        JSONObject jsonObject = JSON.parseObject(result);
        if (BigInteger.ZERO.intValue() == jsonObject.getInteger("errcode")) {
            return true;
        }else {
            throw new RuntimeException("发送失败，错误码：" + jsonObject.getString("errcode"));
        }
    }

    private static Map<String,Object> buildTextMsg(String textStr,Set<String> atPhone){
        Map<String,Object> text = new HashMap<>();
        text.put("content",textStr);
        if(atPhone!=null && atPhone.size() > BigInteger.ZERO.intValue()){
            text.put("mentioned_mobile_list",atPhone);
        }
        Map<String,Object> textMsgInfo = new HashMap<>();
        textMsgInfo.put("msgtype","text");
        textMsgInfo.put("text",text);
        return textMsgInfo;
    }

}
